home *** CD-ROM | disk | FTP | other *** search
/ Programming an RTS Game with Direct3D / Programming an RTS Game with Direct3D.iso / Examples / Chapter 4 / Example 4.11 / app.cpp next >
Encoding:
C/C++ Source or Header  |  2006-08-01  |  7.2 KB  |  267 lines

  1. //////////////////////////////////////////////////////////////
  2. // Example 4.11: Placing Terrain Objects                    //
  3. // Written by: C. Granberg, 2005                            //
  4. //////////////////////////////////////////////////////////////
  5.  
  6. #include <windows.h>
  7. #include <d3dx9.h>
  8. #include "debug.h"
  9. #include "heightMap.h"
  10. #include "terrain.h"
  11. #include "object.h"
  12.  
  13. #define KEYDOWN(vk_code) ((GetAsyncKeyState(vk_code) & 0x8000) ? 1 : 0)
  14. #define KEYUP(vk_code)   ((GetAsyncKeyState(vk_code) & 0x8000) ? 0 : 1)
  15.  
  16. class APPLICATION
  17. {
  18.     public:
  19.         APPLICATION();
  20.         HRESULT Init(HINSTANCE hInstance, int width, int height, bool windowed);
  21.         HRESULT Update(float deltaTime);
  22.         HRESULT Render();
  23.         HRESULT Cleanup();
  24.         HRESULT Quit();
  25.  
  26.     private:
  27.         IDirect3DDevice9* m_pDevice; 
  28.         TERRAIN m_terrain;
  29.  
  30.         float m_angle, m_radius;
  31.         bool m_wireframe;
  32.         HWND m_mainWindow;
  33.         ID3DXFont *m_pFont;
  34. };
  35.  
  36. int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE prevInstance, PSTR cmdLine, int showCmd)
  37. {
  38.     APPLICATION app;
  39.  
  40.     if(FAILED(app.Init(hInstance, 800, 600, true)))
  41.         return 0;
  42.  
  43.     MSG msg;
  44.     memset(&msg, 0, sizeof(MSG));
  45.     int startTime = timeGetTime(); 
  46.  
  47.     while(msg.message != WM_QUIT)
  48.     {
  49.         if(::PeekMessage(&msg, 0, 0, 0, PM_REMOVE))
  50.         {
  51.             ::TranslateMessage(&msg);
  52.             ::DispatchMessage(&msg);
  53.         }
  54.         else
  55.         {    
  56.             int t = timeGetTime();
  57.             float deltaTime = (t - startTime)*0.001f;
  58.  
  59.             app.Update(deltaTime);
  60.             app.Render();
  61.  
  62.             startTime = t;
  63.         }
  64.     }
  65.  
  66.     app.Cleanup();
  67.  
  68.     return msg.wParam;
  69. }
  70.  
  71. APPLICATION::APPLICATION()
  72. {
  73.     m_pDevice = NULL; 
  74.     m_mainWindow = 0;
  75.     m_angle = 0.0f;
  76.     m_radius = 100.0f;
  77.     m_wireframe = false;
  78.     srand(GetTickCount());
  79. }
  80.  
  81. HRESULT APPLICATION::Init(HINSTANCE hInstance, int width, int height, bool windowed)
  82. {
  83.     debug.Print("Application initiated");
  84.  
  85.     //Create Window Class
  86.     WNDCLASS wc;
  87.     memset(&wc, 0, sizeof(WNDCLASS));
  88.     wc.style         = CS_HREDRAW | CS_VREDRAW;
  89.     wc.lpfnWndProc   = (WNDPROC)::DefWindowProc; 
  90.     wc.hInstance     = hInstance;
  91.     wc.lpszClassName = "D3DWND";
  92.  
  93.     //Register Class and Create new Window
  94.     RegisterClass(&wc);
  95.     m_mainWindow = CreateWindow("D3DWND", "Example 4.11: Placing Terrain Objects", WS_EX_TOPMOST, 0, 0, width, height, 0, 0, hInstance, 0); 
  96.     SetCursor(NULL);
  97.     ShowWindow(m_mainWindow, SW_SHOW);
  98.     UpdateWindow(m_mainWindow);
  99.  
  100.     //Create IDirect3D9 Interface
  101.     IDirect3D9* d3d9 = Direct3DCreate9(D3D_SDK_VERSION);
  102.  
  103.     if(d3d9 == NULL)
  104.     {
  105.         debug.Print("Direct3DCreate9() - FAILED");
  106.         return E_FAIL;
  107.     }
  108.  
  109.     //Check that the Device supports what we need from it
  110.     D3DCAPS9 caps;
  111.     d3d9->GetDeviceCaps(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, &caps);
  112.  
  113.     //Hardware Vertex Processing or not?
  114.     int vp = 0;
  115.     if(caps.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT)
  116.         vp = D3DCREATE_HARDWARE_VERTEXPROCESSING;
  117.     else vp = D3DCREATE_SOFTWARE_VERTEXPROCESSING;
  118.  
  119.     //Check vertex & pixelshader versions
  120.     if(caps.VertexShaderVersion < D3DVS_VERSION(2, 0) || caps.PixelShaderVersion < D3DPS_VERSION(2, 0))
  121.     {
  122.         debug.Print("Warning - Your graphic card does not support vertex and pixelshaders version 2.0");
  123.     }
  124.  
  125.     //Set D3DPRESENT_PARAMETERS
  126.     D3DPRESENT_PARAMETERS d3dpp;
  127.     d3dpp.BackBufferWidth            = width;
  128.     d3dpp.BackBufferHeight           = height;
  129.     d3dpp.BackBufferFormat           = D3DFMT_A8R8G8B8;
  130.     d3dpp.BackBufferCount            = 1;
  131.     d3dpp.MultiSampleType            = D3DMULTISAMPLE_NONE;
  132.     d3dpp.MultiSampleQuality         = 0;
  133.     d3dpp.SwapEffect                 = D3DSWAPEFFECT_DISCARD; 
  134.     d3dpp.hDeviceWindow              = m_mainWindow;
  135.     d3dpp.Windowed                   = windowed;
  136.     d3dpp.EnableAutoDepthStencil     = true; 
  137.     d3dpp.AutoDepthStencilFormat     = D3DFMT_D24S8;
  138.     d3dpp.Flags                      = 0;
  139.     d3dpp.FullScreen_RefreshRateInHz = D3DPRESENT_RATE_DEFAULT;
  140.     d3dpp.PresentationInterval       = D3DPRESENT_INTERVAL_IMMEDIATE;
  141.  
  142.     //Create the IDirect3DDevice9
  143.     if(FAILED(d3d9->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, m_mainWindow,
  144.                                  vp, &d3dpp, &m_pDevice)))
  145.     {
  146.         debug.Print("Failed to create IDirect3DDevice9");
  147.         return E_FAIL;
  148.     }
  149.  
  150.     //Release IDirect3D9 interface
  151.     d3d9->Release();
  152.  
  153.     D3DXCreateFont(m_pDevice, 18, 0, 0, 1, false,  
  154.                    DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY,
  155.                    DEFAULT_PITCH | FF_DONTCARE, "Arial", &m_pFont);
  156.  
  157.     LoadObjectResources(m_pDevice);
  158.  
  159.     m_terrain.Init(m_pDevice, INTPOINT(150,150));
  160.  
  161.     //Set sampler state
  162.     for(int i=0;i<4;i++)
  163.     {
  164.         m_pDevice->SetSamplerState(i, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
  165.         m_pDevice->SetSamplerState(i, D3DSAMP_MINFILTER, D3DTEXF_LINEAR);
  166.         m_pDevice->SetSamplerState(i, D3DSAMP_MIPFILTER, D3DTEXF_POINT);
  167.     }
  168.  
  169.     return S_OK;
  170. }
  171.  
  172. HRESULT APPLICATION::Update(float deltaTime)
  173. {
  174.     //Control camera
  175.     m_angle += deltaTime * 0.5f;
  176.     D3DXMATRIX  matWorld, matView, matProj;        
  177.     D3DXVECTOR2 centre = D3DXVECTOR2(m_terrain.m_size.x / 2.0f, m_terrain.m_size.y / 2.0f);
  178.     D3DXVECTOR3 Eye    = D3DXVECTOR3(centre.x + cos(m_angle) * m_radius, m_radius, -centre.y + sin(m_angle) * m_radius);
  179.     D3DXVECTOR3 Lookat = D3DXVECTOR3(centre.x, 0.0f,  -centre.y);
  180.  
  181.     D3DXMatrixIdentity(&matWorld);
  182.     D3DXMatrixLookAtLH(&matView, &Eye, &Lookat, &D3DXVECTOR3(0.0f, 1.0f, 0.0f));
  183.     D3DXMatrixPerspectiveFovLH( &matProj, D3DX_PI/4, 1.3333f, 1.0f, 1000.0f );
  184.  
  185.     m_pDevice->SetTransform( D3DTS_WORLD,      &matWorld );
  186.     m_pDevice->SetTransform( D3DTS_VIEW,       &matView );
  187.     m_pDevice->SetTransform( D3DTS_PROJECTION, &matProj );
  188.     
  189.     if(KEYDOWN('W'))
  190.     {
  191.         m_wireframe = !m_wireframe;
  192.         Sleep(300);
  193.     }
  194.     else if(KEYDOWN(VK_ADD) && m_radius < 200.0f)
  195.     {
  196.         m_radius += deltaTime * 30.0f;
  197.     }
  198.     else if(KEYDOWN(VK_SUBTRACT) && m_radius > 5.0f)
  199.     {
  200.         m_radius -= deltaTime * 30.0f;
  201.     }
  202.     else if(KEYDOWN(VK_SPACE))
  203.     {
  204.         m_terrain.GenerateRandomTerrain(3);
  205.     }
  206.  
  207.     if(KEYDOWN(VK_ESCAPE))
  208.         Quit();
  209.  
  210.     return S_OK;
  211. }    
  212.  
  213. HRESULT APPLICATION::Render()
  214. {
  215.     // Clear the viewport
  216.     m_pDevice->Clear( 0L, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, 0xffffffff, 1.0f, 0L );
  217.  
  218.     // Begin the scene 
  219.     if(SUCCEEDED(m_pDevice->BeginScene()))
  220.     {
  221.         if(m_wireframe)m_pDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_WIREFRAME);    
  222.         else m_pDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
  223.  
  224.         m_terrain.Render();
  225.  
  226.         RECT r[] = {{10, 10, 0, 0}, {10, 30, 0, 0}, {10, 50, 0, 0}};
  227.         m_pFont->DrawText(NULL, "W: Toggle Wireframe", -1, &r[0], DT_LEFT| DT_TOP | DT_NOCLIP, 0xff000000);
  228.         m_pFont->DrawText(NULL, "+/-: Zoom In/Out", -1, &r[1], DT_LEFT| DT_TOP | DT_NOCLIP, 0xff000000);
  229.         m_pFont->DrawText(NULL, "Space: Randomize Terrain", -1, &r[2], DT_LEFT| DT_TOP | DT_NOCLIP, 0xff000000);
  230.         
  231.         char number[50];
  232.         std::string text = itoa(m_terrain.m_objects.size(), number, 10);
  233.         text += " objects";
  234.         RECT rc = {710, 10, 0, 0};
  235.         m_pFont->DrawText(NULL, text.c_str(), -1, &rc, DT_LEFT| DT_TOP | DT_NOCLIP, 0xff000000);
  236.  
  237.         // End the scene.
  238.         m_pDevice->EndScene();
  239.         m_pDevice->Present(0, 0, 0, 0);
  240.     }
  241.  
  242.     return S_OK;
  243. }
  244.  
  245. HRESULT APPLICATION::Cleanup()
  246. {
  247.     try
  248.     {
  249.         m_terrain.Release();
  250.         UnloadObjectResources();
  251.  
  252.         m_pFont->Release();
  253.         m_pDevice->Release();
  254.  
  255.         debug.Print("Application terminated");
  256.     }
  257.     catch(...){}
  258.  
  259.     return S_OK;
  260. }
  261.  
  262. HRESULT APPLICATION::Quit()
  263. {
  264.     ::DestroyWindow(m_mainWindow);
  265.     ::PostQuitMessage(0);
  266.     return S_OK;
  267. }